package com.spark.common.interceptor;

import com.spark.common.core.entity.LoginUser;
import com.spark.common.utils.ReflectUtils;
import com.spark.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Objects;
import java.util.Properties;

/**
 * mybatis-plus拦截器，自动注入创建人、创建时间、修改人、修改时间
 *
 * @author LYCHEE
 * @date 2025/2/14 15:43
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (parameter == null) {
            return invocation.proceed();
        }
        LoginUser user = null;
        try {
            user = SecurityUtils.getUser();
        } catch (Exception ignored) {
        }
        if (Objects.isNull(user)) {
            return invocation.proceed();
        }
        Field[] fields = ReflectUtils.getAllFields(parameter);
        // 插入操作
        if (SqlCommandType.INSERT == sqlCommandType) {
            for (Field field : fields) {
                try {
                    // 创建人
                    if ("createBy".equals(field.getName())) {
                        String createBy = ReflectUtils.getField(parameter, "createBy", String.class);
                        if (StringUtils.isEmpty(createBy) && StringUtils.isNotEmpty(user.getUsername())) {
                            // 注入
                            ReflectUtils.setField(parameter, "createBy", user.getUsername());
                        }
                    }
                    // 创建时间
                    if ("createTime".equals(field.getName())) {
                        Date createTime = ReflectUtils.getField(parameter, "createTime", Date.class);
                        if (Objects.isNull(createTime)) {
                            // 注入
                            ReflectUtils.setField(parameter, "createTime", new Date());
                        }
                    }
                } catch (Exception e) {
                    log.error("插入操作注入参数失败：{}", e.getMessage());
                }
            }
        }
        // 更新操作
        if (SqlCommandType.UPDATE == sqlCommandType) {
            if (parameter instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap<?> p = (MapperMethod.ParamMap<?>) parameter;
                if (p.containsKey("et")) {
                    parameter = p.get("et");
                } else {
                    parameter = p.get("param1");
                }
                if (parameter == null) {
                    return invocation.proceed();
                }
                fields = ReflectUtils.getAllFields(parameter);
            }

            for (Field field : fields) {
                try {
                    // 更新人
                    if ("updateBy".equals(field.getName())) {
                        String updateBy = ReflectUtils.getField(parameter, "updateBy", String.class);
                        if (StringUtils.isEmpty(updateBy) && StringUtils.isNotEmpty(user.getUsername())) {
                            // 注入
                            ReflectUtils.setField(parameter, "updateBy", user.getUsername());
                        }
                    }
                    // 更新时间
                    if ("updateTime".equals(field.getName())) {
                        Date updateTime = ReflectUtils.getField(parameter, "updateTime", Date.class);
                        if (Objects.isNull(updateTime)) {
                            // 注入
                            ReflectUtils.setField(parameter, "updateTime", new Date());
                        }
                    }
                } catch (Exception e) {
                    log.error("更新操作注入参数失败：{}", e.getMessage());
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}
